package api

import (
	"gin/api/helper"
	"gin/config"
	"gin/middleware"
	"gin/model"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)

// 登录方法
func Login(c *gin.Context) {
	var form model.User
	var data gin.H
	var code int
	var token string
	err := c.ShouldBindJSON(&form)
	if err != nil {
		data = helper.Out(config.ERROR)
	} else {
		form, code = model.Login(form.Name, form.Password)

		if code == config.SUCCESS {
			token, code = middleware.SetToken(form.Name)
		}
		data = helper.Out(code)
		if token != "" {
			data["data"] = map[string]string{
				"username": form.Name,
				"token":    token,
				"id":       strconv.Itoa(int(form.ID)),
				"role":     strconv.Itoa(form.Role),
			}
		}
	}
	c.JSON(http.StatusOK, data)
}

// 查询登录状态
func LoginStatus(c *gin.Context) {
	var data gin.H
	var result map[string]string
	token := c.DefaultQuery("token", "")
	if token == "" {
		data = helper.Out(config.ParamError)
	} else {
		res, code := middleware.CheckToken(token)
		if code == config.SUCCESS {
			var user model.User
			user, code = model.GetInfoByName(res.Username)
			result = map[string]string{
				"username": res.Username,
				"role":     strconv.Itoa(user.Role),
			}
		}
		data = helper.Out(code, result)
	}

	c.JSON(http.StatusOK, data)
}
